﻿namespace TestTool.GUI.Utils
{
    using System;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Xml.Serialization;
    using TestTool.GUI.Data;
    using TestTool.Tests.Engine;

    internal class DatasheetReportGenerator : IReportGenerator
    {
        public event Action<Exception> OnException;

        public event Action OnReportSaved;

        public void CreateReport(string fileName, TestLogFull log)
        {
            try
            {
                Datasheet o = new Datasheet {
                    Features = log.Features
                };
                if (log.DeviceInformation != null)
                {
                    o.Capabilities = log.DeviceInformation.Capabilities;
                    o.DeviceInformation = new DeviceInformation();
                    o.DeviceInformation.FirmwareVersion = log.DeviceInformation.FirmwareVersion;
                    o.DeviceInformation.HardwareID = log.DeviceInformation.HardwareID;
                    o.DeviceInformation.Manufacturer = log.DeviceInformation.Manufacturer;
                    o.DeviceInformation.Model = log.DeviceInformation.Model;
                    o.DeviceInformation.SerialNumber = log.DeviceInformation.SerialNumber;
                }
                o.TestInformation = new TestInformation();
                o.TestInformation.TestDate = log.TestExecutionTime;
                o.TestInformation.ProductName = log.ProductName;
                if (log.Application != null)
                {
                    o.TestInformation.ToolVersion = log.Application.ToolVersion;
                }
                o.ManagementSettings = log.ManagementSettings;
                using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    new XmlSerializer(typeof(Datasheet)).Serialize((Stream) stream, o);
                }
                this.RaiseOnReportSaved();
            }
            catch (Exception exception)
            {
                this.RaiseOnException(exception);
            }
        }

        private void RaiseOnException(Exception exception)
        {
            if (this.OnException != null)
            {
                this.OnException(exception);
            }
        }

        private void RaiseOnReportSaved()
        {
            if (this.OnReportSaved != null)
            {
                this.OnReportSaved();
            }
        }
    }
}

